package com.weishuang.monitor.leader.config.client;

import com.weishuang.monitor.leader.config.security.handler.CustomAuthenticationFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
public class ClientCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Autowired
    private ClientAuthenticationSuccessHandler clientAuthenticationSuccessHandler;

    @Autowired
    private ClientAuthenticationProvider clientAuthenticationProvider;

    @Override
    public void configure(HttpSecurity builder) throws Exception {
        ClientAbstractAuthenticationProcessingFilter clientAbstractAuthenticationProcessingFilter = new ClientAbstractAuthenticationProcessingFilter();
        clientAbstractAuthenticationProcessingFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        clientAbstractAuthenticationProcessingFilter.setAuthenticationSuccessHandler(clientAuthenticationSuccessHandler);
        clientAbstractAuthenticationProcessingFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);

        builder.authenticationProvider(clientAuthenticationProvider)
                .addFilterAfter(clientAbstractAuthenticationProcessingFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
